/**
 * Copyright 2019-2024 覃海林(qinhaisenlin@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package com.qinhailin.common.visit;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Aop;
import com.jfinal.core.Controller;
import com.qinhailin.common.entity.ILoginUser;
import com.qinhailin.common.kit.IpKit;
import com.qinhailin.common.model.SysUser;
import com.qinhailin.pub.login.service.LoginService;

/**
 * 访问者工具
 * 
 * @author hhs
 * @date 2015年7月20日
 */
public class VisitorUtil {
	public static final String VISITOR_KEY = "visitor";
	public static final ThreadLocal<ILoginUser> LOGIN_USER = new ThreadLocal<ILoginUser>();

	/**
	 *
	 * <p>
	 * 获取线程变量：登录用户
	 * </p>
	 * 
	 * @return
	 *         <p>
	 * 		2017年9月7日
	 *         </p>
	 * @author hhs
	 */
	public static ILoginUser getLoginUser() {
		return LOGIN_USER.get();
	}

	public static void setLoginUser(ILoginUser loginUser) {
		if (LOGIN_USER.get() == null) {
			LOGIN_USER.set(loginUser);
		}
	}

	public static void setVisitor(Visitor v, HttpSession session) {
		if (getVisitor(session) != null) {
			removeVisitor(session);
		}
		session.setAttribute(VISITOR_KEY, v);
	}

	/**
	 * 获取访问者
	 * 
	 * @param session
	 * @return
	 */
	public static Visitor getVisitor(HttpSession session) {
		if (session == null) {
			return null;
		}
		//为了解决偶尔出现的转换异常
		try {		
			Visitor v = (Visitor) session.getAttribute(VISITOR_KEY);
			return v;
		} catch (Exception e) {
			e.printStackTrace();
			session.removeAttribute(VISITOR_KEY);
			return null;
		}
	}

	public static void removeVisitor(HttpSession session) {
		if (session != null) {
			session.removeAttribute(VISITOR_KEY);
		}
	}

	/**
	 * 获取访问者的数据
	 * 
	 * @param session
	 * @return ComUser
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getVisitorUserData(HttpSession session) {
		if (session == null) {
			return null;
		}
		try {
			if (session.getAttribute(VISITOR_KEY) == null) {
				return null;
			} else {
				Visitor v = (Visitor) session.getAttribute(VISITOR_KEY);
				T t = (T) v.getUserData();
				return t;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取登录用户
	 * 
	 * @author hhs
	 * @date 2016年7月19日
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T extends ILoginUser> T getUser(HttpSession session) {
		if (session == null) {
			return null;
		}
		try {
			if (session.getAttribute(VISITOR_KEY) == null) {
				return null;
			} else {
				Visitor v = (Visitor) session.getAttribute(VISITOR_KEY);
				T t = (T) v.getUserData();
				return t;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	//cookie登陆
	static LoginService loginService=Aop.get(LoginService.class);
	
	/**
	 * 通过cookie获取登陆信息
	 * @param c
	 * @return
	 */
	public static Visitor getVisitor(Controller c){
		SysUser loginAccount = null;
		Visitor vs=null;
		String sessionId = c.getCookie(LoginService.sessionIdName);
		if(sessionId==null)
			sessionId=c.getSessionAttr("sessionId");
		
		if (sessionId != null) {
			loginAccount = loginService.getLoginAccountWithSessionId(sessionId);
			if (loginAccount == null) {
				String loginIp = IpKit.getRealIp(c.getRequest());
				loginAccount = loginService.loginWithSessionId(sessionId, loginIp);
			}
			if (loginAccount != null) {
				vs=loginService.getVistor(loginAccount);
			} else {
				c.removeCookie(LoginService.sessionIdName); // cookie 登录未成功，证明该 cookie 已经没有用处，删之
				c.removeSessionAttr("sessionId");
			}
		}
		//用于前端按钮权限控制
		c.set("vs", vs);
		return vs;
	}
	
	/**
	 * cookie退出登陆
	 * @param c
	 */
	public static void removeVisitor(Controller c){
		String sessionId = c.getCookie(LoginService.sessionIdName);
		loginService.logout(sessionId);
		c.removeCookie(LoginService.sessionIdName);
	}
}
